package ee.az.tetris;

import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.ToolTipManager;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

/**
 * @author Artur Zinatullin (artur.zinatullin@gmail.com) 2010
 */
public class Glass extends JTable {

	private static final long serialVersionUID = 1L;

	public static final Color EMPTY = Color.darkGray;
	public static final Color FLOATING = Color.white;
	public static final Color FIXED = Color.lightGray;

	public Glass(int width, int height) {
		super(new TableModel(width, height));
		
		setTableHeader(null);
		setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
		setRowSelectionAllowed(false);
		setCellSelectionEnabled(false);
		
		setColumnsWidth(this);
		ToolTipManager.sharedInstance().unregisterComponent(this);
		initGlass();
	}

	public Color getValue(int col, int row) {
		return (Color) dataModel.getValueAt(row, col);
	}
	public void setValue(Color value, int col, int row) {
		dataModel.setValueAt(value, row, col);
	}
	
	private void setColumnsWidth(JTable table) {
		TableColumn column = null;
		for (int i = 0; i < dataModel.getColumnCount(); i++) {
			column = getColumnModel().getColumn(i);
			column.setPreferredWidth(15);
			column.setCellRenderer(new ColorRenderer());
		}

	}

	private static class TableModel extends DefaultTableModel {
		private static final long serialVersionUID = 1L;
		
		public TableModel(int width, int height) {
			super(height, width);
		}
		
		@Override
		public boolean isCellEditable(int row, int column) {
			return false;
		}
	}
	
	private class ColorRenderer extends DefaultTableCellRenderer {
		private static final long serialVersionUID = 1L;

		public ColorRenderer() {
			setHorizontalAlignment(JLabel.CENTER);
		}

		@Override
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
			Component tableCellRendererComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
			if (value instanceof Color) {
				setBackground((Color)value);
			}
			setText("");
			return tableCellRendererComponent;
		}
	}

	private void initGlass() {
		for (int col = 0; col < dataModel.getColumnCount(); col++) {
			for (int row = 0; row < dataModel.getRowCount(); row++) {
				dataModel.setValueAt(EMPTY, row, col);
			}
		}
	}
}
